package com.xinke.edu.mypetadoption;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.navigation.NavigationBarView;
import com.xinke.edu.mypetadoption.databinding.ActivityMainBinding;
import com.xinke.edu.mypetadoption.fragment.Home.HomeFragment;
import com.xinke.edu.mypetadoption.fragment.Mine.MineFragment;

public class MainActivity extends AppCompatActivity {
    // 视图绑定对象，用于访问布局中的控件
    ActivityMainBinding binding;
    // HOME Fragment实例
    HomeFragment homeFragment = new HomeFragment();
    // MINE Fragment实例
    MineFragment mineFragment = new MineFragment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化视图绑定，关联activity_main.xml布局
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        // 设置当前Activity的布局为绑定类的根布局
        setContentView(binding.getRoot());

        // 应用启动时，默认显示首页Fragment
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment, homeFragment) // 替换R.id.fragment容器为首页Fragment
                .commit();

        // 给底部导航栏设置“项选中监听器”，监听用户点击事件
        binding.navgationview.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // 用于存储要切换的目标Fragment
                Fragment fragment = null;

                // 根据点击的导航项ID，确定要切换的Fragment
                if (item.getItemId() == R.id.HOME) {
                    fragment = homeFragment; // 点击“HOME”导航项，切换到首页Fragment
                } else if (item.getItemId() == R.id.MINE) {
                    fragment = mineFragment; // 点击“MINE”导航项，切换到个人中心Fragment
                }

                // 执行Fragment切换操作
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment, fragment) // 替换容器为目标Fragment
                        .commit();

                return true; // 返回true表示点击了该点击事件，确保导航项状态正确
            }
        });
    }
}